#include "task.h"

using namespace dxy::reflect;

namespace dxy::easyWebServer
{

Task::Task()
{
    m_request = make_shared<Request>(-1);
    m_response = make_shared<Response>(-1);
}

Task::Task(int fd)
    : m_fd(fd)
{
    m_request = make_shared<Request>(fd);
    m_response = make_shared<Response>(fd);
}

Task::~Task()
{
    
}

void Task::run()
{
    try
    {
        process();
    }
    catch(const std::exception& e)
    {
        error(e.what());
    }
    shutdown(m_fd, SHUT_RDWR);
}

void Task::process()
{
    m_request->parse();
    std::string idx1, idx2, parameter;
    parse(m_request->m_url, idx1, idx2, parameter);
    info(m_request->m_url.c_str());
    size_t ret = m_conn.existFile(m_request->m_url);
    if(ret != -1)
    {
        m_response->setHead();
        m_response->add("Content-Length", to_string(ret));
        m_response->send();
        size_t sendlen = m_conn.sendFile(m_fd, m_request->m_url, ret);
        return;
    }
    m_request->set("parameter", parameter);
    if(DxyReflectClass::getInstance().isExistClass(idx1) == false ||
       DxyReflectClass::getInstance().isExistFunction(idx1, idx2) == false)
    {
        idx1 = "Index";
        idx2 = "_404";
    }
    auto obj = DxyReflectClass::getInstance().getClassByName(idx1);
    obj->set<std::shared_ptr<Request>>(idx1, "m_request", m_request);
    obj->set<std::shared_ptr<Response>>(idx1, "m_response", m_response);
    obj->call(idx1, idx2);
    obj->get<std::shared_ptr<Request>>(idx1, "m_request", m_request);
    obj->get<std::shared_ptr<Response>>(idx1, "m_response", m_response);
    m_response->send();
}

void Task::parse(std::string & src, std::string & idx1, std::string & idx2, std::string & parameter)
{
    std::vector<std::string> spliturl, splitFirst, splitSecond;
    // boost::split(spliturl, src, boost::is_any_of("?"));
    splitRegex(spliturl, src, "?");
    src = spliturl[0];
    if(spliturl[0].size() > 0)
    {
        splitRegex(splitFirst, spliturl[0], "/");
        // boost::split(splitFirst, spliturl[0], boost::is_any_of("/"));
    }
    if(spliturl.size() > 1 && spliturl[1].size() > 0)
    {
        parameter = spliturl[1];
    }
    if(splitFirst.size() != 3)
    {
        idx1 = "Index";
        idx2 = "_404";
        parameter = "";
        return;
    }
    idx1 = splitFirst[1];
    idx2 = splitFirst[2];
}


}

